#include "Tools/RIVIAToolBase.h"

#include "IRIVIABrushes.h"
#include "IRIVIAProject.h"

using namespace cv;

RIVIAToolBase::RIVIAToolBase()
{

}

RIVIAToolBase::~RIVIAToolBase()
{

}

void RIVIAToolBase::genROIRect(cv::Mat &imagemat, cv::Mat &brushmat, int x, int y,
                               cv::Rect &roi_rect, cv::Rect &brushroi_rect)
{
    int brush_w = brushmat.cols;
    int brush_h = brushmat.rows;
    int image_w = imagemat.cols;
    int image_h = imagemat.rows;

    int ltx = x - (int)(brush_w/2);
    int lty = y - (int)(brush_h/2);
    int rbx = x + (int)(brush_w/2);
    int rby = y + (int)(brush_h/2);

    int roilt_x = ltx > 0 ? ltx : 0;
    int roilt_y = lty > 0 ? lty : 0;
    int roirb_x = rbx > (image_w - 1) ? (image_w - 1) : rbx;
    int roirb_y = rby > (image_h - 1) ? (image_h - 1) : rby;

    int roi_w = roirb_x - roilt_x + 1;
    int roi_h = roirb_y - roilt_y + 1;

    roi_rect = cv::Rect(roilt_x, roilt_y, roi_w, roi_h);

    int brushroilt_x = 0;
    int brushroilt_y = 0;
    if(ltx < 0 || lty < 0)
    {
        brushroilt_x = roilt_x - ltx;
        brushroilt_y = roilt_y - lty;
    }

    brushroi_rect = cv::Rect(brushroilt_x, brushroilt_y, roi_w, roi_h);
}

void RIVIAToolBase::updateROI(int x, int y)
{
    Mat brushmat = IRIVIABrushes().getCurBrushMat();
    Mat imagemat = IRIVIAProject::getInstance()->getCurMat();
    Mat imagematproc = IRIVIAProject::getInstance()->getCurMatProc();

    if(x > (imagemat.cols - 1) || x < 0 || y > (imagemat.rows - 1) || y < 0)
        return;

    Rect roi_rect, brushroi_rect;
    genROIRect(imagemat, brushmat, x, y, roi_rect, brushroi_rect);

    Mat brushroi_mat(brushmat, brushroi_rect);
    m_brushroi_mat = brushroi_mat;
    Mat roi_mat(imagemat, roi_rect);
    m_roi_mat = roi_mat;
    Mat roi_matproc(imagematproc, roi_rect);
    m_roi_matproc = roi_matproc;
}
